import json
import os
import requests

from typing import Union, List, Dict

import sys
sys.path.append(os.path.abspath('../..'))

from local_pwd import Yi_API_KEY, Yi_SECRET_KEY


def send_req(msg:Union[str, Dict], url):
    if isinstance(msg, str):
        msg = {
                "messages": [
                        {"role":"user","content": msg}
                    ]
                }        
    url += get_access_token()
    payload = json.dumps(msg)
    headers = {
        'Content-Type': 'application/json'
    }
    response = requests.request("POST", url, headers=headers, data=payload)
    return json.loads(response.text)


def get_access_token():
    url = "https://aip.baidubce.com/oauth/2.0/token"
    params = {"grant_type": "client_credentials", "client_id": Yi_API_KEY, "client_secret": Yi_SECRET_KEY}
    return str(requests.post(url, params=params).json().get("access_token"))


if __name__ == '__main__':
    res = send_req("请你做一下自我介绍吧！")
    print(res)
